import logging
from commens import get_back_data
from commens import dump_to_json


data = None
intermiData = None
count = 0


def construct_relation(intermiD,paramD):
    global count
    relationMap = {}
    # for k,v in intermiD.items():
    #     mml = {'参数': paramD[k],'尾命令':[]}
    #     for subMml in v:
    #         if subMml in paramD.keys():
    #             mml['尾命令'].append({subMml:paramD[subMml]})
    #     relationMap[k] = mml
    for k,asso in intermiD.items():
        mml = {'参数': paramD[k], '尾命令': {}}
        for as_point,as_e in asso.items():
            for subMml in as_e.keys():
                logREFORM.debug('%s %s [%s]'%(k,subMml,as_point))
                if subMml in paramD.keys():
                    if subMml in mml['尾命令']:
                        mml['尾命令']['%s_%d'%(subMml,count)] = {'参数': paramD[subMml], '关联点': as_point, '关联内容': as_e[subMml]}
                        count += 1
                    else:
                        mml['尾命令'][subMml] = {'参数':paramD[subMml],'关联点':as_point,'关联内容':as_e[subMml]}
        relationMap[k] = mml
    return relationMap


def main():
    global data
    global  intermiData
    data = get_back_data('PARAM.json')
    intermiData = get_back_data('INTERMI.json')
    res = construct_relation(intermiData,data)
    print("生成了%d条数据"%len(res))
    dump_to_json(res,'REFORM.json')
    print("Done")


if __name__ == '__main__':
    logREFORM = logging.getLogger("REFORM")
    logREFORM.setLevel(logging.DEBUG)
    hdREFORM = logging.FileHandler("REFORM.log", mode='w', encoding='utf-8')
    ch = logging.StreamHandler()
    ch.setLevel(logging.WARNING)
    hdREFORM.setLevel(logging.DEBUG)
    logREFORM.addHandler(hdREFORM)
    logREFORM.addHandler(ch)
    main()